package com.mogujie.tt.ui.fragment;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mogujie.tt.DB.entity.UserEntity;
import com.mogujie.tt.DB.sp.LoginSp;
import com.mogujie.tt.DB.sp.RegisterSp;
import com.mogujie.tt.DB.sp.SystemConfigSp;
import com.mogujie.tt.R;
import com.mogujie.tt.app.UpdateDetection;
import com.mogujie.tt.config.MessageConstant;
import com.mogujie.tt.config.RegisterConstant;
import com.mogujie.tt.config.SysConstant;
import com.mogujie.tt.imservice.entity.ImageMessage;
import com.mogujie.tt.imservice.event.ConcurrentUserDetailsEvent;
import com.mogujie.tt.imservice.service.LoadImageService;
import com.mogujie.tt.ui.activity.RegisterActivity;
import com.mogujie.tt.ui.helper.PhotoHelper;
import com.mogujie.tt.utils.HttpUtilsApache;
import com.mogujie.tt.utils.IMUIHelper;
import com.mogujie.tt.imservice.event.UserInfoEvent;
import com.mogujie.tt.imservice.manager.IMLoginManager;
import com.mogujie.tt.imservice.service.IMService;
import com.mogujie.tt.ui.activity.SettingActivity;
import com.mogujie.tt.imservice.support.IMServiceConnector;
import com.mogujie.tt.utils.FileUtil;
import com.mogujie.tt.ui.widget.IMBaseImageView;
import com.mogujie.tt.utils.ImageUtil;
import com.mogujie.tt.utils.JsonUtil;
import com.mogujie.tt.utils.MoGuHttpClient;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.mogujie.tt.app.IMApplication;
import com.mogujie.tt.ui.activity.ChgpwdActivity;
import com.mogujie.tt.ui.activity.GesturesActivity;
import com.mogujie.tt.ui.activity.GuideGesturePasswordActivity;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;

public class MyFragment extends MainFragment {
	private View curView = null;
	private View contentView;
	private View exitView;
    private View clearView;
    private View settingView;

    private View setdetailsView;
    private View setupdateView;
    private View cgpwdView;
    private View Gestures;

    private IMServiceConnector imServiceConnector = new IMServiceConnector(){
        @Override
        public void onServiceDisconnected() {}

        @Override
        public void onIMServiceConnected() {
            if (curView == null) {
                return;
            }
            IMService imService = imServiceConnector.getIMService();
            if (imService == null) {
                return;
            }
            if (!imService.getContactManager().isUserDataReady()) {
                logger.i("detail#contact data are not ready");
            } else {
                init(imService);
            }
        }
    };

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {


		imServiceConnector.connect(getActivity());
        EventBus.getDefault().register(this);//注册事件

		if (null != curView) {
			((ViewGroup) curView.getParent()).removeView(curView);
			return curView;
		}
		curView = inflater.inflate(R.layout.tt_fragment_my, topContentView);

		initRes();

		return curView;
	}

	/**
	 * @Description 初始化资源
	 */
	private void initRes() {
		super.init(curView);
		
		contentView = curView.findViewById(R.id.content);
        exitView = curView.findViewById(R.id.exitPage);
        clearView = curView.findViewById(R.id.clearPage);
        settingView = curView.findViewById(R.id.settingPage);
        setdetailsView = curView.findViewById(R.id.detailsPage);
        setupdateView = curView.findViewById(R.id.updatePage);
        cgpwdView = curView.findViewById(R.id.changePwd);
        Gestures = curView.findViewById(R.id.Gestures);

        //清除图片缓存按钮
        clearView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), android.R.style.Theme_Holo_Light_Dialog));
                LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View dialog_view = inflater.inflate(R.layout.tt_custom_dialog, null);
                final EditText editText = (EditText)dialog_view.findViewById(R.id.dialog_edit_content);
                editText.setVisibility(View.GONE);
                TextView textText = (TextView)dialog_view.findViewById(R.id.dialog_title);
                textText.setText(R.string.clear_cache_tip);
                builder.setView(dialog_view);

                builder.setPositiveButton(getString(R.string.tt_ok), new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ImageLoader.getInstance().clearMemoryCache();
                        ImageLoader.getInstance().clearDiskCache();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                FileUtil.deleteHistoryFiles(new File(Environment.getExternalStorageDirectory().toString()
                                        + File.separator + "MGJ-IM"+File.separator),System.currentTimeMillis());
                                Toast toast = Toast.makeText(getActivity(),R.string.thumb_remove_finish,Toast.LENGTH_LONG);
                                toast.setGravity(Gravity.CENTER,0,0);
                                toast.show();
                            }
                        },500);

                        dialog.dismiss();
                    }
                });

                builder.setNegativeButton(getString(R.string.tt_cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
                builder.show();
            }
        });

        //退出
        exitView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {

                AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), android.R.style.Theme_Holo_Light_Dialog));
                LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View dialog_view = inflater.inflate(R.layout.tt_custom_dialog, null);
                final EditText editText = (EditText)dialog_view.findViewById(R.id.dialog_edit_content);
                editText.setVisibility(View.GONE);
                TextView textText = (TextView)dialog_view.findViewById(R.id.dialog_title);
                textText.setText(R.string.exit_teamtalk_tip);
                builder.setView(dialog_view);
                builder.setPositiveButton(getString(R.string.tt_ok), new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        IMLoginManager.instance().setKickout(false);
                        IMLoginManager.instance().logOut();
                        getActivity().finish();
                        dialog.dismiss();
                    }
                });

                builder.setNegativeButton(getString(R.string.tt_cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                       dialogInterface.dismiss();
                    }
                });
                builder.show();

			}
		});

        //无功能
        settingView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到配置页面
                startActivity(new Intent(MyFragment.this.getActivity(), SettingActivity.class));
            }
        });
		
		cgpwdView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                    startActivity(new Intent(MyFragment.this.getActivity(), ChgpwdActivity.class));

            }
        });

        Gestures.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            if(!IMApplication.getInstance().getLockPatternUtils().savedPatternExists()){
                startActivity(new Intent(MyFragment.this.getActivity(), GuideGesturePasswordActivity.class));
            }else{
                startActivity(new Intent(MyFragment.this.getActivity(), GesturesActivity.class));
            }
            }
        });
		hideContent();

		// 设置顶部标题栏
		setTopTitle(getActivity().getString(R.string.page_me));
		// 设置页面其它控件

        //设置详细信息页面
        setdetailsView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("signUpPage",false);
                intent.setClass(getActivity(), RegisterActivity.class);
                getActivity().startActivity(intent);

            }
        });
        //设置更新
        setupdateView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new UpdateDetection(getActivity()).checkUpdateInfo();
            }
        });

	}

	private void hideContent() {
		if (contentView != null) {
			contentView.setVisibility(View.GONE);
		}
	}

	private void showContent() {
		if (contentView != null) {
			contentView.setVisibility(View.VISIBLE);
		}
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
        // 应该放在这里嘛??
        imServiceConnector.disconnect(getActivity());
        EventBus.getDefault().unregister(this);//销毁事件
	}

	@Override
	protected void initHandler() {
	}

    public void onEventMainThread(UserInfoEvent event){
        switch (event){
            case USER_INFO_OK:
                init(imServiceConnector.getIMService());
        }
    }

    TextView nickNameView;
    IMBaseImageView portraitImageView;
    private void init(IMService imService) {
		showContent();
		hideProgressBar();
		
		if (imService == null) {
			return;
		}

		final UserEntity loginContact = imService.getLoginManager().getLoginInfo();
		if (loginContact == null) {
			return;
		}
        nickNameView = (TextView) curView.findViewById(R.id.nickName);//昵称
		TextView userNameView = (TextView) curView.findViewById(R.id.userName);//用户名
        portraitImageView = (IMBaseImageView) curView.findViewById(R.id.user_portrait);

        //设置昵称 与用户名
		nickNameView.setText(loginContact.getMainName());
		userNameView.setText(loginContact.getRealName());

        //头像设置
        portraitImageView.setDefaultImageRes(R.drawable.tt_default_user_portrait_corner);
        portraitImageView.setCorner(15);
        portraitImageView.setImageResource(R.drawable.tt_default_user_portrait_corner);
        portraitImageView.setImageUrl(loginContact.getAvatar());

        //用户容器
        RelativeLayout userContainer = (RelativeLayout) curView.findViewById(R.id.user_container);
		userContainer.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
                Log.v("","1111111111111111111111");
				IMUIHelper.openUserProfileActivity(getActivity(), loginContact.getPeerId());
			}
		});
	}

    private void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                item.delete();
            }
        }
        else {
            logger.e("fragment#deleteFilesByDirectory, failed");
        }
    }
    /**
     * ----------------------------event 事件驱动----------------------------
     */
    public void onEventMainThread(ConcurrentUserDetailsEvent.ConcurrentNicknameEvent event) {
        switch (event) {
            case MODIFY_NICKNAME:
                nickNameView.setText(RegisterSp.instance().getSpDetailedInfo().getDetailedNickName().toString().trim());//设置昵称
                portraitImageView.setDefaultImageRes(R.drawable.tt_default_user_portrait_corner);
                portraitImageView.setCorner(15);
                portraitImageView.setImageResource(R.drawable.tt_default_user_portrait_corner);
                String path = RegisterConstant.PHOTO_PATH + RegisterConstant.IMAGE_FILE_TAILOR_NAME;
                if(new File(path).exists()){
                    portraitImageView.setImageUrl(RegisterSp.instance().getSpDetailedInfo().getDetailedHeadPortrait());//设置头像
                }
                break;
            case NO_MODIFY_NICKNAME:

                break;
        }
    }

}
